package com.woniu.woniu_bx.controller;

import com.woniu.woniu_bx.exception.ManagerExistsException;
import com.woniu.woniu_bx.pojo.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author : 王泰元
 * @className: GlobalAdvisor
 * @description: TODO
 * @date : 2022/8/29 10:45
 */
@RestControllerAdvice(basePackages = "com.woniu.woniu_bx.controller")
public class GlobalAdvisor {


    /**
     * controller 的统一异常处理
     *
     * @param e 异常
     * @return 返回 msg 为异常信息的响应实体类对象
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity handlerException(Exception e) {
        e.printStackTrace();
        String message = "系统维护中，请稍候再试";

        if (StringUtils.hasLength(e.getMessage())) {
            message = e.getMessage();
        }

        return ResponseEntity.FAIL(message, null);
    }


    /**
     * 无访问权限异常处理（security抛出）
     *
     * @param e AccessDeniedException
     * @return ResponseEntity.NO_PERM
     */
//    @ExceptionHandler(AccessDeniedException.class)
//    public ResponseEntity handlerAccessDeniedException(AccessDeniedException e) {
//        e.printStackTrace();
//        return ResponseEntity.NO_PERM("没有访问权限", null);
//    }
    @ExceptionHandler(ManagerExistsException.class)
    public ResponseEntity handlerManagerExistsException(Exception e) {
        e.printStackTrace();
        String message = "管理员账号已存在，请重新注册！";

        if (StringUtils.hasLength(e.getMessage())) {
            message = e.getMessage();
        }

        return new ResponseEntity<>(501, message, null);
    }


}
